//
//  ALiPay.m
//  SXH
//
//  Created by Jack on 15/9/24.
//  Copyright © 2015年 lyss. All rights reserved.
//

#import "ALiPay.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "BaseViewController.h"
#import "OrderEntity.h"

@implementation ALiPay

-(void)postOrder:(NSString *)tradeNO productName:(NSString *)productName productDescription:(NSString *)productDescription amount:(NSString *)amount VC:(BaseViewController *)vc orderFlag:(NSString *)orderFlag{
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2088021078655750";
//    NSString *seller = @"trigerchen@leyouss.com";
    NSString *seller = @"leyou@leyouss.com";
    
    NSString *privateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOmVj8t6pG2D05zUk00rcND1OJX1UaEad5MMRzIxLvDTwwNHhJIKBm7PayFtToINgwzeR2uY2OPf9wUY8HaryJsMLZLVDWsXY2TqM1Vf/8cZWeH2oWxrSB6I7rINkUn9nQibNEbiPoN5l0B0WKR8CDRgeHpqMVM40sByoXmm6y4tAgMBAAECgYARmKO5d2a1nU2urdDe6lvYUfDOUymwEjdZy339iPj5SWqSb6vL+Jddd6ChZwOYBn6N1JzavSvxlqicKLHMrsowxxPgMeOu6FeEU5pNogkoKVd3tntSGuJJKyVohsGWnqPWxftt7g5HBkN5lFg0dYKNXfS+BqORWevQYUCbAJyFvQJBAPjG/E9vdYFKP9FWge2h0WHmkof721gB0BREjn9aONPQNuqsayPDrq/G8TlNMwDEQxAFWMJ9zDR+c4H0HdVuDJ8CQQDwXaeylIhUe1IMOsWi3F46I949LUnRc9S7xwnGoCeAD23hks3SfAUJJxF7j7s7VGLzUMDtxrayVzBQS6dbfsWzAkBEjTh7fyAnB1m8ipT08VEsJAgetpUDlERNQXLuvuLH4yku02IWkdZyE2TnQFGclXhRUtfZiCacFHgpyCXsaQ3LAkBLRGiA6TYPjlZQ8g51QyBWgGjVK1tUNTtGWbtb8UatOSelXT0KTj+dcBhvYsC0gWZC3uSrEHChQ+AjJK2RXw81AkEA6n1ra5oxAxTB/Vm4U33rPR7UCtcdLONZMRaftsLzOO1bOKwU7QLKNgr4mykxSFLEKTRHQGb5YSEywACU1SQl6w==";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = tradeNO;//[dic objectForKey:@"order_num"]; //订单ID（由商家自行制定）
    order.productName = productName;//@"商品标题"; //商品标题
    order.productDescription = productDescription;//@"商品描述"; //商品描述
    order.amount = amount;//[NSString stringWithFormat:@"%.2f",0.01]; //商品价格
    order.notifyURL = @"http://api.leyouss.com/shop/order_pay/cb_ali_pay";
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = ALIPAY_APPSCHEME;
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
//        NSURL * myURL_APP_A = [NSURL URLWithString:@"alipay:"];
//        if (![[UIApplication sharedApplication] canOpenURL:myURL_APP_A]) {
//            //如果没有安装支付宝客户端那么需要安装
//            UIAlertView *message = [[UIAlertView alloc]initWithTitle:@"提示信息" message:@"您还没有安装支付宝钱包!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//            [message show];
//            return;
//        }
        
//        NSArray *array = [[UIApplication sharedApplication] windows];
//        UIWindow* win=[array objectAtIndex:0];
//        [win setHidden:NO];
        
//        //跳转 AppStore 下载支付宝
//        NSString * URLString = @"http://itunes.apple.com/cn/app/id535715926?mt=8";
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            if([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]){
                //删除本地订单
                NSUserDefaults *orderDefault = [NSUserDefaults standardUserDefaults];
                NSMutableArray *mutableArrayTemp = [NSMutableArray arrayWithArray:[orderDefault objectForKey:@"OrderEntityList"]];
                for(int i=0;i<[mutableArrayTemp count];i++){
                    OrderEntity *orderEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayTemp objectAtIndex:i]];
                    if([orderEntity.order_num isEqualToString: tradeNO]){
                        [mutableArrayTemp removeObjectAtIndex:i];
                    }
                }
                //记住要转换成不可变数组类型
                NSArray * array = [NSArray arrayWithArray:mutableArrayTemp];
                [orderDefault setObject:array forKey:@"OrderEntityList"];
            }
            
            [vc handlePayResult:[resultDic objectForKey:@"resultStatus"]];
            NSLog(@"reslut = %@",resultDic);
        }];
    }
}
@end
